/***********************************************************************************************************
 *** @Author         : jiabao
 *** @Description    : 把任一年份转为天干地支纪年法
 *** @Date           : 2025-08-30 11:05:47
 *** @FilePath       : \demo_cc\algorithm\tiangandizhi\main.cpp
 ***********************************************************************************************************/

#include <iostream>
#include <string>
#include "base_all.h"
using namespace std;
u32 str_get_char_num(const string &str)
{
    u32 charNum = 0;
    for (auto it = str.begin(); it != str.end(); it++)
    {
        if ((*it & 0xc0) != 0x80)
        {
            ++charNum;
        }
    }
    return charNum;
}
string str_get_n_char(const string &str, u32 n)
{
    string nChar = "";
    u08 charLen = 1;
    u32 index = 0;
    u32 charNum = str_get_char_num(str);
    if (n > charNum)
    {
        return nChar;
    }
    for (s32 i = 0; i <= n && index < str.size(); i++)
    {
        charLen = 1;
        if ((str[index] & 0xf8) == 0xf0)
        {
            charLen = 4; // 占用4个字节，前5位为11110
        }
        else if ((str[index] & 0xf0) == 0xe0)
        {
            charLen = 3; // 占用3个字节，前4位为1110
        }
        else if ((str[index] & 0xe0) == 0xc0)
        {
            charLen = 2; // 占用2个字节，前3位为110
        }
        index += charLen;
    }
    index -= charLen;
    for (s32 i = 0; i < charLen; i++)
    {
        nChar += str[index + i];
    }
    return nChar;
}

void str_test()
{
    u32 charNum = 0;
    string str1 = "中12国";
    cout << str1.size() << endl;
    for (auto it = str1.begin(); it != str1.end(); it++)
    {
        printf("0x%x ", *it);
    }
    printf("\n");
    charNum = str_get_char_num(str1);
    cout << str1 << " 字符个数:" << charNum << endl;
    for (s32 i = 0; i < charNum; i++)
    {
        cout << "第" << i << "个字符:" << str_get_n_char(str1, i) << endl;
    }

    string str2 = "1452大大大大的撒非常";
    charNum = str_get_char_num(str2);
    cout << str2 << " 字符个数:" << charNum << endl;
    for (s32 i = 0; i < charNum; i++)
    {
        cout << "第" << i << "个字符:" << str_get_n_char(str2, i) << endl;
    }
}

u32 year_standard(s32 year)
{
    u32 yearStandard = 0;
    if (year >= 3)
    {
        return year;
    }
    if (year < 0)
    {
        yearStandard = -year;
    }
    return year + (yearStandard / 60 + 1) * 60;
}
int main()
{
    // str_test();

    const string tiangan = "甲乙丙丁戊己庚辛壬癸";
    const string dizhi = "子丑寅卯辰巳午未申酉戌亥";
    s32 years = 0;
    u32 yearStandard = 0;
    u08 tianganIndex = 0, dizhiIndex = 0;

    while (1)
    {
        cout << "请输入要转换为天干地支纪年的年份：（支持公元前以及公元后）";
        cin >> years;
        yearStandard = year_standard(years);
        tianganIndex = ((yearStandard - 3) % 10 + 9) % 10;
        dizhiIndex = ((yearStandard - 3) % 12 + 11) % 12;
        cout << "天干：" << str_get_n_char(tiangan,tianganIndex) << "  地支：" << str_get_n_char(dizhi,dizhiIndex) << endl;
    }

    return 0;
}
